package com.central.post.service.serviceImp

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.convert.NumberChineseFormatter
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.central.common.entity.NewGood
import com.central.common.enum.CommentTypeEnum
import com.central.common.enum.LikeTypeEnum
import com.central.common.enum.ResultCode
import com.central.common.feign.CommentService
import com.central.common.feign.LikeService
import com.central.common.model.*
import com.central.common.service.impl.SuperServiceImpl
import com.central.common.utils.toDateBegin
import com.central.common.utils.toDateEnd
import com.central.common.utils.weekStr
import com.central.post.mapper.NewGoodMapper
import com.central.post.pojo.newGood.*
import com.central.post.service.NewGoodService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @author  fly
 * @date  2021/5/26 14:51
 * @version 1.0
 */
@Service
open class NewGoodServiceImp : SuperServiceImpl<NewGoodMapper, NewGood>(), NewGoodService {


    @Autowired
    private lateinit var commentService: CommentService

    @Autowired
    private lateinit var likeService: LikeService


    override fun saveOrUpdateNewGood(newGoodDto: NewGoodDto, userId: Long): CommonResult<Boolean> = success(
        saveOrUpdate(NewGood().apply {
            BeanUtil.copyProperties(newGoodDto, NewGood)
            createBy = userId
        })
    , "操作上新商品成功")

    override fun removeNewGood(ids: String): CommonResult<Boolean> = success(
        removeByIds(ids.split(","))
    , "删除上新商品成功")

    override fun getNewGoodListByTime(newGoodSearchDto: NewGoodSearchDto, pageVo: PageVo): CommonResult<Page<NewGoodList>> =
        page(Page(pageVo.pageNumber!!, pageVo.pageSize!!), KtQueryWrapper(NewGood::class.java)
            .eq(newGoodSearchDto.goodType != 0, NewGood::goodType, newGoodSearchDto.goodType)
            .gt(NewGood::createTime, newGoodSearchDto.year!! toDateBegin newGoodSearchDto.month!!)
            .le(NewGood::createTime, newGoodSearchDto.year!! toDateEnd newGoodSearchDto.month!!)
            .orderByDesc(NewGood::createTime))
            .run {
                records.takeIf { it.isNotEmpty() }?.let {
                    success(
                        Page<NewGoodList>(current, size, total, isSearchCount).apply {
                            records = it.groupBy { DateUtil.dayOfMonth(it.createTime) }.map { (key, value) ->
                                NewGoodList().apply {
                                    time = "$key / ${newGoodSearchDto.month}(周 ${NumberChineseFormatter.format(
                                        newGoodSearchDto.month!!.weekStr(key, newGoodSearchDto.year!!).toDouble(),
                                        true,
                                        true
                                    )})"
                                    newGoodListVos = value.mapNotNull { getNewGoodListVo(it.id) }
                                }
                            }
                        }
                        , "获取上新列表成功")
                } ?: failed(ResultCode.NO_CONTENT)
            }

    override fun getNewGoodDetail(id: Long, sysUser: SysUser, pageVo: PageVo): CommonResult<NewGoodDetailVo> =
        getNewGoodDetailVo(id, sysUser, pageVo)?.run { success(this, "获取详情成功") }
            ?: failed(ResultCode.NO_CONTENT)

    override fun subscribeNewGood(id: Long, sysUser: SysUser): CommonResult<Boolean> = getById(id)?.run {
        subscribeUser = subscribeUser ?.let { subscribeUser + ",${sysUser.id}" } ?: sysUser.id.toString()
        success(updateById(this), "订阅成功")
    } ?: failed(ResultCode.NO_CONTENT)


    private fun getNewGoodListVo(id: Long): NewGoodListVo? = getById(id)?.let {
        NewGoodListVo().apply {
            BeanUtil.copyProperties(it, this)
            goodPicList = it.goodPics?.split(",")
            likeNum = likeService.getLikeNum(id, LikeTypeEnum.NEW_GOOD).likeNum?.toLong()
            commentNum = commentService.getCommentNumByRelevanceId(id, CommentTypeEnum.NEW_GOOD)
        }
    }

    private fun getNewGoodDetailVo(id: Long, sysUser: SysUser, pageVo: PageVo): NewGoodDetailVo? = getById(id)?.let {
        NewGoodDetailVo().apply {
            BeanUtil.copyProperties(it, this)
            goodPicList = it.goodPics?.split(",")
            goodTime = DateUtil.parseDate(it.goodTime)
            booleanLike = likeService.booleanLike(id, sysUser.id, LikeTypeEnum.NEW_GOOD).booleanLike
            commentInfo = commentService.getCommentVoListByRelevanceId(id, sysUser, pageVo, CommentTypeEnum.NEW_GOOD)
            booleanSubscribe = it.subscribeUser?.split(",")?.contains(sysUser.id.toString())
        }
    }

}
